package com.cmii.sjw.department.control.jsc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cmii.sjw.department.control.jsc.mapper.IndustryEducationMapper;
import com.cmii.sjw.department.control.jsc.mapper.SchoolMapMapper;
import com.cmii.sjw.department.control.jsc.model.IndustryEducation;
import com.cmii.sjw.department.control.jsc.model.SchoolInfo;
import com.cmii.sjw.department.control.jsc.model.params.SchoolInfoParams;
import com.cmii.sjw.department.control.jsc.service.IndustryEducationService;
import com.cmii.sjw.department.control.jsc.util.Result;
import com.cmii.sjw.department.control.jsc.vo.SchoolResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class IndustryEducationServiceImpl extends ServiceImpl<IndustryEducationMapper, IndustryEducation> implements IndustryEducationService {

    @Autowired
    private  IndustryEducationMapper industryEducationMapper;

    @Autowired
    private  SchoolMapMapper schoolInfoMapper;

    @Override
    public List<String> getAllIndustryNames() {

        QueryWrapper<IndustryEducation> queryWrapper = new QueryWrapper<>();

        return this.list(queryWrapper).stream()
                .map(IndustryEducation::getIndustryName)
                .distinct()
                .collect(Collectors.toList());
    }

    public List<String> getIndustryNamesByManagementArea(String managementAreaName) {
        // 查询管理区名称对应的学校列表
        QueryWrapper<SchoolInfo> schoolQueryWrapper = new QueryWrapper<>();
        schoolQueryWrapper.eq("management_area_name", managementAreaName);
        List<SchoolInfo> schools = schoolInfoMapper.selectList(schoolQueryWrapper);

        if (schools.isEmpty()) {
            return List.of();
        }

        // 提取学校名称列表
        List<String> schoolNames = schools.stream().map(SchoolInfo::getName).collect(Collectors.toList());

        // 查询这些学校对应的 industry_name
        QueryWrapper<IndustryEducation> industryQueryWrapper = new QueryWrapper<>();
        industryQueryWrapper.in("school_name", schoolNames);
        return this.list(industryQueryWrapper).stream()
                .map(IndustryEducation::getIndustryName)
                .distinct()
                .collect(Collectors.toList());
    }
    @Override
    public SchoolResponse getSchoolsByIndustryName(String industryName) {

        LambdaQueryWrapper<IndustryEducation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(IndustryEducation::getIndustryName, industryName);
        List<IndustryEducation> industryEducations = this.list(queryWrapper);

        Map<String, List<String>> areaSchoolsMap = new HashMap<>();

        for (IndustryEducation industryEducation : industryEducations) {
            String schoolName = industryEducation.getSchoolName();
            SchoolInfo schoolInfo = schoolInfoMapper.selectOne(
                    Wrappers.<SchoolInfo>lambdaQuery().eq(SchoolInfo::getName, schoolName)
            );

            if (schoolInfo != null) {
                String areaName = schoolInfo.getManagementAreaName();
                areaSchoolsMap.putIfAbsent(areaName, new ArrayList<>());
                areaSchoolsMap.get(areaName).add(schoolName);
            }
        }

        // 计算总学校数量（去重）
        int totalCount = areaSchoolsMap.values().stream()
                .flatMap(List::stream)
                .collect(Collectors.toSet())
                .size();

        List<Map<String, String>> result = new ArrayList<>();

        for (Map.Entry<String, List<String>> entry : areaSchoolsMap.entrySet()) {
            String areaName = entry.getKey();
            int count = entry.getValue().size();
            String combinedSchoolNames = String.join("，", entry.getValue());

            Map<String, String> entryMap = new HashMap<>();
            entryMap.put("areaname", areaName + " (" + count + ")");
            entryMap.put("schools", combinedSchoolNames);
            result.add(entryMap);
        }
        return new SchoolResponse(totalCount, result);
    }

    /**
     * 获取行业教育地图详情
     * @param params
     * @return
     */
    @Override
    public Result industryEducationMapDetailed(SchoolInfoParams params) {
        Map<String, Object> result = new HashMap<>();
        //查询重庆市默认查询全部
        if("重庆市".equals(params.getAreaName())) params.setAreaName(null);

        List<SchoolInfo> schoolList = schoolInfoMapper.industryEducationMapDetailed(params.getAreaName(),params.getName(),params.getIndustryName());
        result.put("schoolList", schoolList);

        return Result.success(result);
    }
}